/**
 * 后端接口预留模块
 * 
 * 核心功能：
 * - 预留真实后端API接口
 * - 统一接口管理
 * - 环境切换支持
 * 
 * 最小实现调用方式：
 * import * as backendApi from '@/api/backend'
 * const result = await backendApi.uploadCoordinateFile(deviceId, file)
 */

import axios from 'axios'

// 后端API基础配置
const API_CONFIG = {
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
}

// 创建后端API实例
const backendApi = axios.create(API_CONFIG)

// 请求拦截器 - 添加认证token
backendApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    console.log(`后端API请求: ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('后端API请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一错误处理
backendApi.interceptors.response.use(
  (response) => {
    console.log(`后端API响应: ${response.status} ${response.config.url}`)
    return response
  },
  (error) => {
    console.error('后端API响应错误:', error.response?.status, error.message)
    
    // 统一错误处理
    if (error.response?.status === 401) {
      // 未授权，清除token并跳转登录
      localStorage.removeItem('auth_token')
      window.location.href = '/login'
    }
    
    return Promise.reject(error)
  }
)

/**
 * 设备管理相关接口
 */

// 获取设备列表
export const getDevices = (params = {}) => {
  return backendApi.get('/devices', { params })
}

// 获取设备详情
export const getDevice = (deviceId) => {
  return backendApi.get(`/devices/${deviceId}`)
}

// 创建设备
export const createDevice = (deviceData) => {
  return backendApi.post('/devices', deviceData)
}

// 更新设备
export const updateDevice = (deviceId, deviceData) => {
  return backendApi.put(`/devices/${deviceId}`, deviceData)
}

// 删除设备
export const deleteDevice = (deviceId) => {
  return backendApi.delete(`/devices/${deviceId}`)
}

/**
 * 文件上传相关接口
 */

// 上传设备图片
export const uploadDeviceImages = (deviceId, files) => {
  const formData = new FormData()
  
  // 支持多文件上传
  if (Array.isArray(files)) {
    files.forEach((file, index) => {
      formData.append(`images[${index}]`, file)
    })
  } else {
    formData.append('image', files)
  }
  
  return backendApi.post(`/devices/${deviceId}/images`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout: 60000 // 文件上传超时时间延长
  })
}

// 上传坐标文件
export const uploadCoordinateFile = (deviceId, file) => {
  const formData = new FormData()
  formData.append('coordinate_file', file)
  
  return backendApi.post(`/devices/${deviceId}/coordinates`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout: 30000
  })
}

// 解析坐标文件
export const parseCoordinateFile = (deviceId, imageId) => {
  return backendApi.post(`/devices/${deviceId}/images/${imageId}/parse-coordinates`)
}

/**
 * 模拟相关接口
 */

// 处理设备点击事件
export const processDeviceClick = (deviceId, clickData) => {
  return backendApi.post(`/devices/${deviceId}/simulate/click`, clickData)
}

// 获取设备模拟状态
export const getSimulationState = (deviceId) => {
  return backendApi.get(`/devices/${deviceId}/simulate/state`)
}

// 重置设备模拟状态
export const resetSimulationState = (deviceId) => {
  return backendApi.post(`/devices/${deviceId}/simulate/reset`)
}

/**
 * 坐标管理相关接口
 */

// 获取图片的可点击区域
export const getImageClickableAreas = (deviceId, imageId) => {
  return backendApi.get(`/devices/${deviceId}/images/${imageId}/areas`)
}

// 更新图片的可点击区域
export const updateImageClickableAreas = (deviceId, imageId, areas) => {
  return backendApi.put(`/devices/${deviceId}/images/${imageId}/areas`, { areas })
}

// 添加可点击区域
export const addClickableArea = (deviceId, imageId, areaData) => {
  return backendApi.post(`/devices/${deviceId}/images/${imageId}/areas`, areaData)
}

// 删除可点击区域
export const deleteClickableArea = (deviceId, imageId, areaId) => {
  return backendApi.delete(`/devices/${deviceId}/images/${imageId}/areas/${areaId}`)
}

/**
 * 数据分析相关接口
 */

// 获取设备使用统计
export const getDeviceUsageStats = (deviceId, timeRange = '7d') => {
  return backendApi.get(`/devices/${deviceId}/stats`, {
    params: { time_range: timeRange }
  })
}

// 获取点击热力图数据
export const getClickHeatmapData = (deviceId, imageId, timeRange = '7d') => {
  return backendApi.get(`/devices/${deviceId}/images/${imageId}/heatmap`, {
    params: { time_range: timeRange }
  })
}

// 导出设备数据
export const exportDeviceData = (deviceId, format = 'json') => {
  return backendApi.get(`/devices/${deviceId}/export`, {
    params: { format },
    responseType: 'blob'
  })
}

/**
 * 系统管理相关接口
 */

// 获取系统状态
export const getSystemStatus = () => {
  return backendApi.get('/system/status')
}

// 获取API版本信息
export const getApiVersion = () => {
  return backendApi.get('/system/version')
}

/**
 * 工具函数
 */

// 检查后端连接状态
export const checkBackendConnection = async () => {
  try {
    await getSystemStatus()
    return true
  } catch (error) {
    console.warn('后端连接检查失败:', error.message)
    return false
  }
}

// 获取上传进度回调
export const createUploadProgressCallback = (onProgress) => {
  return {
    onUploadProgress: (progressEvent) => {
      if (progressEvent.lengthComputable && onProgress) {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
        onProgress(percentCompleted)
      }
    }
  }
}

export default backendApi
